package com.project.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

@ServerEndpoint("/webSocket")
@Service
@Slf4j
public class CSCWebSocket {

    public static final String USER_PATH = "/audit/user";
    public static final String SUPPLIER_PATH = "/audit/supplier";
    public static final String PROMOTION_PATH = "/audit/promotion";
    public static final String PROCURE_APPLY_PATH = "/audit/procureApply";
    public static final String PURCHASE_PATH = "/audit/purchase";
    public static final String SUPPLY_ORDER_PATH = "/audit/supplyOrder";
    public static final String OFFER_PATH = "/audit/offer";
    public static final String USER_RECHARGE_PATH = "/audit/userRecharge";
    public static final String SUPPLY_MONITOR_PATH = "/audit/supplyInfoMonitor";
    public static final String USER_ORDER_REFUND_PATH = "/audit/userOrderRefund";
    public static final String SUPPLIER_ORDER_REFUND_PATH = "/audit/supplierOrderRefund";

        //concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
        //虽然@Component默认是单例模式的，但springboot还是会为每个websocket连接初始化一个bean，所以可以用一个静态set保存起来。
        //  注：底下WebSocket是当前类名
    private static Set<CSCWebSocket> webSockets = new HashSet<>();
    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;
    /**
     * 用户ID
     */
    private String userId;

    //客户端和服务器建立连接时触发
    @OnOpen
    public void onOpen(Session s, @PathParam("token") String token) throws Exception {
        this.session = s;
        webSockets.add(this);
        System.err.println("websocket连接");
    }

    //客户端和服务器断开连接时触发
    @OnClose
    public void onClose(Session s) {
        System.err.println("websocket连接关闭");
    }

    //客户端向服务器发送消息时触发
    @OnMessage
    public void onMessage(String msg, Session s) throws IOException {

    }

    public void SendMessage(String msg) throws IOException {
        for (CSCWebSocket webSocket : webSockets) {
            try {
                if (webSocket.session.isOpen()) {
                    webSocket.session.getBasicRemote().sendText(msg);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    //websocket发生异常时触发
    @OnError
    public void onError(Throwable e) throws IOException {
        session.getBasicRemote().sendText("websocket连接发送异常");
    }


}
